package cn.wy.org.controller;

import cn.wy.basic.annotation.PreAuthorize;
import cn.wy.basic.util.AjaxResult;
import cn.wy.basic.util.PageList;
import cn.wy.org.domain.Department;
import cn.wy.org.query.DepartmentQuery;
import cn.wy.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping ("/department")

public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;

//    GET http://localhost:80/dept/1    | 获取单个部门 |
    @GetMapping ("/{id}")
    @PreAuthorize(name = "获取单个部门",sn="department:findOne")
    public Department findOne(@PathVariable ("id") Long id){
        Department deptOne = departmentService.findOne(id);
        return deptOne;
    }
//    GET http://localhost:80/dept      | 获取所有部门 |
    @GetMapping
    @PreAuthorize(name = "获取所有部门",sn="department:findAll")
    public List<Department> findAll() {
        return departmentService.findAll();
    }
//    Put http://localhost:80/dept     | 创建或者修改单个部门 |
    @PutMapping
    @PreAuthorize(name = "添加或者修改单个部门",sn="department:addOrUpdate")
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            if(department.getId() == null){
                departmentService.insert(department);
            }else {
                departmentService.update(department);
            }
            return new AjaxResult();
        }catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败！");
        }
    }

//    DELETE http://localhost:80/dept/1 | 删除单个资源 |
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "删除单个部门",sn="department:delete")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            departmentService.delete(id);
            return new AjaxResult();
        }catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "删除失败");
        }
    }
    //    Post http://localhost:80/dept      | 分页查询 |
    @PostMapping
    @PreAuthorize(name = "分页列表查询",sn="department:pageQuery")
    public PageList<Department> pageQuery(@RequestBody DepartmentQuery departmentQuery){
       return departmentService.queryPage(departmentQuery);
    }
    // Patch http://localhost:8080/department/1 批量删除
    @PatchMapping
    @PreAuthorize(name = "批量删除",sn="department:patchDel")
    public AjaxResult patchDel(@RequestBody List<Long> ids) {
        try {
            departmentService.patchDel(ids);
            return new AjaxResult();
        }catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "删除失败");
        }
    }

    @GetMapping("/deptTree")
    @PreAuthorize(name = "获取级联部门",sn="department:deptTreeAll")
    public List<Department> deptTreeAll() {
        return departmentService.deptTree();
    }
}
